package com.rockville.ufone.rssdata;

import java.util.HashMap;

import org.apache.log4j.Logger;

import com.rockville.httpRequest.HttpRequestUrl;
import com.rockville.ufone.DBProc;

public class WeatherParser implements Runnable {

	private static final Logger log = Logger.getLogger(WeatherParser.class);
	private static HashMap<String, String> hmParams = new HashMap<String, String>();
	static {
	    hmParams.put("Chiniot",     "http://weather.yahoo.com/pakistan/punjab/chiniot-2210871/?unit=c");
	    hmParams.put("Faisalabad",  "http://weather.yahoo.com/pakistan/punjab/shah-faisalabad-2211574/?unit=c");
	    hmParams.put("Gujranwala",  "http://weather.yahoo.com/pakistan/punjab/gujranwala-2210977/?unit=c");
	    hmParams.put("Gujrat",      "http://weather.yahoo.com/pakistan/punjab/gujrat-2197074/?unit=c");
	    hmParams.put("Kasur",       "http://weather.yahoo.com/pakistan/punjab/kasor-2211104/?unit=c");
	    hmParams.put("Jhang Sadar", "http://weather.yahoo.com/pakistan/punjab/jhang-sadr-2198674/?unit=c");
	    hmParams.put("Lahore",      "http://weather.yahoo.com/pakistan/punjab/lahore-2211177/?unit=c");
	    hmParams.put("Multan",      "http://weather.yahoo.com/pakistan/punjab/multan-2211269/?unit=c");
	    hmParams.put("Okara",       "http://weather.yahoo.com/pakistan/punjab/okara-2211313/?unit=c");
	    hmParams.put("Rawalpindi",  "http://weather.yahoo.com/pakistan/punjab/r%C3%A5walpindi-2211387/?unit=c");
	    hmParams.put("Sahiwal",     "http://weather.yahoo.com/pakistan/punjab/montgomery-2211404/?unit=c");
	    hmParams.put("Sargodha",    "http://weather.yahoo.com/pakistan/punjab/sargodha-2211425/?unit=c");
	    hmParams.put("Shekhupura",  "http://weather.yahoo.com/pakistan/punjab/qila-sheikhupura-2211456/?unit=c");
	    hmParams.put("Sialkot",     "http://weather.yahoo.com/pakistan/punjab/sialkot-2211467/?unit=c");
	    
	    hmParams.put("Hyderabad",   "http://weather.yahoo.com/pakistan/sindh/haidarabad-2211024/?unit=c");
	    hmParams.put("Karachi",     "http://weather.yahoo.com/pakistan/sindh/karachi-2211096/?unit=c");
	    hmParams.put("Thatta",      "http://weather.yahoo.com/pakistan/sindh/thatta-2211531/?unit=c");
	    hmParams.put("Sukkur",      "http://weather.yahoo.com/pakistan/sindh/sukkur-2211490/?unit=c");
	    hmParams.put("Nawabshah",   "http://weather.yahoo.com/pakistan/sindh/nawabshah-2211296/?unit=c");
	    
	    hmParams.put("Islamabad",   "http://weather.yahoo.com/pakistan/islamabad/islamabad-2211027/?unit=c");
	    hmParams.put("Peshawar",    "http://weather.yahoo.com/pakistan/federally-administered-tribal-areas/peshawar-2211344/?unit=c");
	    
	    hmParams.put("Kohat",       "http://weather.yahoo.com/pakistan/north-west-frontier/kohat-2211150/?unit=c");
	    hmParams.put("Mardan",      "http://weather.yahoo.com/pakistan/north-west-frontier/mardan-2211223/?unit=c");
	    
	    hmParams.put("Quetta",      "http://weather.yahoo.com/pakistan/balochistan/quetta-2211369/?unit=c");

	    hmParams.put("Delhi",       "http://weather.yahoo.com/india/delhi/new-delhi-2295019/?unit=c");
	    hmParams.put("Toronto",     "http://weather.yahoo.com/canada/ontario/toronto-4118/?unit=c");
	    hmParams.put("Dhaka",       "http://weather.yahoo.com/bangladesh/dhaka/dhaka-1915035/?unit=c");
	    hmParams.put("Melbourne",   "http://weather.yahoo.com/australia/victoria/melbourne-international-airport-23388202/?unit=c");
	    hmParams.put("Berlin",      "http://weather.yahoo.com/germany/berlin/berlin-638242/?unit=c");
	    hmParams.put("Barcelona",   "http://weather.yahoo.com/spain/catalonia/barcelona-753692/?unit=c");
	    hmParams.put("Dubai",       "http://weather.yahoo.com/united-arab-emirates/dubai/dubai-1940345/?unit=c");
	    hmParams.put("Madinah",     "http://weather.yahoo.com/saudi-arabia/al-madinah/madinah-international-airport-12517353/?unit=c");
	    hmParams.put("Riyadh",      "http://weather.yahoo.com/saudi-arabia/ar-riyad/riyadh-1939753/?unit=c");
	    hmParams.put("Beijing",     "http://weather.yahoo.com/china/beijing/beijing-international-convention-centre-12906653/?unit=c");
	    hmParams.put("Newyork",     "http://weather.yahoo.com/united-states/new-york/new-york-2459115/?unit=c");
	    hmParams.put("Manchester",  "http://weather.yahoo.com/england/greater-manchester/manchester-28218/?unit=c");
	    hmParams.put("London",      "http://weather.yahoo.com/england/greater-london/london-44418/?unit=c");
	}
	
	@Override
	public void run() {
		log.info("** WeatherParser STARTED **");
	    try {
			DBProc db = DBProc.getInstance();
			String headline = "";
			StringBuffer sb = new StringBuffer();
			headline = "<div class=\"sectionHeader_Text\"><span class=\"sectionHeader_TextHeading\">Weather Summary</span></div>";
		    
		    sb.append("<div class=\"weatherHeading\"></div>");
		    sb.append(parseWeatherSummary( HttpRequestUrl.getURLResponse("http://weather.yahooapis.com/forecastrss?p=PKXX0008&u=c") ));
		    
		    sb.append("<div class=\"weatherHeading\"></div>");
		    sb.append(parseWeatherSummary( HttpRequestUrl.getURLResponse("http://weather.yahooapis.com/forecastrss?p=PKXX0011&u=c") ));
		    
		    sb.append("<div class=\"weatherHeading\"></div>");
		    sb.append(parseWeatherSummary( HttpRequestUrl.getURLResponse("http://weather.yahooapis.com/forecastrss?p=PKXX0006&u=c") ));
		    String text = sb.toString();
			text = java.net.URLDecoder.decode(text, "UTF-8");

			db.updateWeatherData("Summary", headline, text);
			
			for(String city : hmParams.keySet()) {
				headline = "Weather forecast for "+city;
			    text = parseWeatherDetails( HttpRequestUrl.getURLResponse( hmParams.get(city) ) );
				db.updateWeatherData(city, headline, text);
			}
	    } catch (Exception e) {
			log.error("", e);
		}
	    log.info("------------- WeatherParser Task FINISHED -------------");
	}

	public static String parseWeatherDetails(String fileContents) {
	    String strTemp = "";
	    String topLine = "";
	    String todayCondition = "", todayTemperature = "", todaySummary = "", todayDetails = "", forecast = "", city = "";

	    int begIndex = 0;
	    int endIndex = 0;

	    try {

	        // get the city
	        /*
	        begIndex = fileContents.indexOf("yw-breadcrumb");
	        endIndex = fileContents.indexOf("</div>", begIndex);
	        if(begIndex > -1 && endIndex > -1) {
	            strTemp = fileContents.substring(begIndex, endIndex);

	            begIndex = strTemp.lastIndexOf("<li>");
	            endIndex = strTemp.lastIndexOf("</li>");

	            if(begIndex > -1 && endIndex > -1)
	                city = strTemp.substring(begIndex + 4, endIndex);
	        }
	        */
	        
	        begIndex = fileContents.indexOf("yw-forecast");
	        endIndex = fileContents.indexOf("yw-alerts");
	        if(begIndex > -1 && endIndex > -1)
	            fileContents = fileContents.substring(begIndex, endIndex);

	        // get the dateTime at which the wweather was chacked
	        // <em>Current conditions as of 11:55 am PKT</em>
	        begIndex = fileContents.indexOf("<em>")+4;
	        endIndex = fileContents.indexOf("</em>");
	        if(begIndex > 3 && endIndex > -1) {
	            topLine = fileContents.substring(begIndex, endIndex);
	            fileContents = fileContents.substring(endIndex+5);
	        }

	        // get Today's Condition
	        //<div id="yw-cond">Haze</div>
	        begIndex = fileContents.indexOf("yw-cond")+7;
	        begIndex = fileContents.indexOf(">", begIndex)+1;
	        endIndex = fileContents.indexOf("</div>");
	        if(begIndex > 3 && endIndex > -1) {
	            todayCondition = fileContents.substring(begIndex, endIndex);
	            fileContents = fileContents.substring(endIndex+6);
	        }

	        // get Today's Details
	        begIndex = fileContents.indexOf("<dl>")+4;
	        endIndex = fileContents.indexOf("</dl>");
	        if(begIndex > 3 && endIndex > -1) {
	            todayDetails = fileContents.substring(begIndex, endIndex);
	            fileContents = fileContents.substring(endIndex+5);
	        }

	        begIndex = fileContents.indexOf("forecast-temp");
	        if(begIndex > -1)
	            fileContents = fileContents.substring(begIndex);

	        // get Today's Temperature
	        // <div id="yw-temp">14</div>
	        begIndex = fileContents.indexOf("yw-temp")+7;
	        begIndex = fileContents.indexOf(">", begIndex)+1;
	        endIndex = fileContents.indexOf("</div>");
	        if(begIndex > 3 && endIndex > -1) {
	            todayTemperature = fileContents.substring(begIndex, endIndex);
	            fileContents = fileContents.substring(endIndex+6);
	        }

	        // get Today's Temperature
	        begIndex = fileContents.indexOf("<p>")+3;
	        endIndex = fileContents.indexOf("</p>");
	        if(begIndex > 2 && endIndex > -1) {
	            todaySummary = fileContents.substring(begIndex, endIndex);
	            fileContents = fileContents.substring(endIndex+4);
	        }

	        // get 5 Day Forecast
	        begIndex = fileContents.indexOf("<table");
	        endIndex = fileContents.indexOf("</table>")+8;
	        if(begIndex > -1 && endIndex > 7) {
	            forecast = fileContents.substring(begIndex, endIndex);
	            fileContents = "";

	            // replace the last <th> element
	            //begIndex = forecast.indexOf("class=")-4;
	            //endIndex = forecast.indexOf("</th>", begIndex)+5;
	            //strTemp = forecast.substring(begIndex, endIndex);
	            //forecast = forecast.replace(strTemp, "");
	            forecast = forecast.replaceAll("<th\\s*class(.|\\s)*?</th>", "");

	            // replace the <td> which contains extended forecast link
	            begIndex = forecast.indexOf("rowspan=")-4;
	            endIndex = forecast.indexOf("</td>", begIndex)+5;
	            strTemp = forecast.substring(begIndex, endIndex);
	            forecast = forecast.replace(strTemp, "");
	            //forecast = forecast.replaceAll("<td\\s*rowspan(.|\\s)*?</td>", "");

	            forecast = forecast.replaceAll("<div\\s*style?=", "<div class=\"iconDiv\" style=");
	            
	            forecast = forecast.replaceFirst("<table>", "<table class=\"tbl_forecast\">");
	        }
	    }
	    catch(Exception ex) {
	        return ex.getMessage();
	    }
	    
	    /*
	    <style>
	        .temperature {font-size:120%; padding: 5px 0; }
	        .condition {font-weight: bold; padding-right: 10px; }
	        .summary {font-size: 85%; padding-bottom: 5px; }
	        .forecast {margin-top: 5px; border: 1px solid black; text-align: center; }
	        .forecast th {background-color: black; width: 15%; color: white;}
	        .fiveday-icons td {padding-bottom: 5px; }
	        .iconDiv {padding-top: 30px; background-position: 50% 0; background-repeat: no-repeat; font-weight: bold; }
	        .tbl_forecast {text-align: center; }
	    </style>
	    */
	    strTemp = "<div>" +
	            "<div class=\"temperature\"><span class=\"condition\"> "+todayCondition+" </span>"+todayTemperature+"</div>" +
	            "<div class=\"summary\">"+todaySummary+"</div>" +
	            forecast +
	            "</div>";
	    // Before Returning Create a div based layout and place the strings in their appropriate places
	    //return topLine + todayCondition + todayTemperature + todaySummary + "<br><br>" + forecast;
	    
	    strTemp = strTemp.replaceAll("&#176;", " C");
	    
	    return strTemp;
	}

	public String parseWeatherSummary(String strRawData) {
	    int begIndex = 0;
	    int endIndex = 0;
	    
	    String strTitle = "", strImage = "", strResult = "";
	    
	    try {
	        begIndex = strRawData.indexOf("<item>");
	        endIndex = strRawData.indexOf("</item>");
	        if(begIndex > -1 && endIndex > -1)
	            strRawData = strRawData.substring(begIndex+6, endIndex);
	        
	        // get title
	        begIndex = strRawData.indexOf("<title>");
	        endIndex = strRawData.indexOf("</title>");
	        if(begIndex > -1 && endIndex > -1)
	            strTitle = strRawData.substring(begIndex+7, endIndex);
	        
	        // get Condition text, which will be used to show the image from local repository
	        begIndex = strRawData.indexOf("text");
	        if(begIndex > -1)
	            strImage = strRawData.substring(begIndex+4, strRawData.indexOf("\"", begIndex+4+3));
	        
	        strImage = strImage.replace("=", "");
	        strImage = strImage.replace("\"", "");
	        
	        // get the weather details
	        begIndex = strRawData.indexOf("<![CDATA[");
	        endIndex = strRawData.indexOf("]]>");
	        if(begIndex > -1 && endIndex > -1)
	            strRawData = strRawData.substring(begIndex+9, endIndex);

	        strRawData = strRawData.substring(0, strRawData.indexOf("<a"));
	        strRawData = strRawData.replaceAll("<img\\s*src(.|\\s)*?>", "");
	        
	        strRawData = strRawData.replace("<b>Current Conditions:</b>", "");
	        strRawData = strRawData.replace("<BR /><BR />", "<br />");
	        strRawData = strRawData.replace("<br /><br />", "<br />");
	    }
	    catch(Exception ex) {
	        return "<p>Currently not available.</p>";
	    }
	    
	    strRawData = strRawData.replaceFirst(strImage, "<img class=\"weatherImage\" src=\"images/weather/"+strImage.toLowerCase()+".gif\" />"+strImage);
	    /*
	    // Styles moved to Database
	    .divWeather {text-align: left; }
	    .weatherImage {padding-right: 5px; padding-bottom: 2px; vertical-align: middle; }
	    .weatherHeading {font-weight: bold; font-decoration: underline; }
	    */
	    strResult += "<div class=\"divWeather\">" +
	            "<div class=\"weatherHeading\">"+ strTitle +"</div>" +
	            ""+ strRawData +"</div>";
	    
	    return strResult;
	}	
}
